import { defineStore } from 'pinia'
import { login, register } from '@/api/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
    state: () => ({
        avatar: sessionStorage.getItem('avatar') || 'default-avatar',  // 修改这里
        token: sessionStorage.getItem('token') || null,
        userInfo: JSON.parse(sessionStorage.getItem('userInfo') || 'null'),
        showAuthModal: false
    }),
    getters: {
        avatarUrl: (state) => {
            const avatars = {
                'default-avatar': new URL('../assets/images/defaultAvatar.webp', import.meta.url).href,
                'user-avatar': new URL('../assets/images/avatar.webp', import.meta.url).href
            }
            return avatars[state.avatar] || state.avatar
        },
        isLoggedIn: (state) => !!state.token
    },
    actions: {
        setToken(token) {
            this.token = token
            sessionStorage.setItem('token', token)
        },
        setUserInfo(userInfo) {
            this.userInfo = userInfo
            this.avatar = userInfo.avatar || 'user-avatar'  // 确保avatar同步更新
            sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
            sessionStorage.setItem('avatar', this.avatar)  // 新增存储
        },
        clearAuth() {
            this.token = null
            this.userInfo = null
            this.avatar = 'default-avatar'
            sessionStorage.removeItem('token')
            sessionStorage.removeItem('userInfo')
            sessionStorage.removeItem('avatar')
            removeToken() // 新增：清理cookie中的token
        },
        async login(loginData) {
            try {
                this.avatar = 'user-avatar';
                const response = await login(loginData)
                this.setToken(response.data.token)  // 明确获取token字段
                this.setUserInfo(response.data.userInfo)  // 确保也设置用户信息
                router.push('/')
                return Promise.resolve()
            } catch (error) {
                return Promise.reject(error)
            }
        },
        async register(registerData) {
            try {
                const response = await register(registerData)
                // 注册成功后可以自动登录或跳转到登录页
                return Promise.resolve(response)
            } catch (error) {
                return Promise.reject(error)
            }
        },
        logout() {
            this.clearAuth()
            this.avatar = 'default-avatar'
            router.push('/login')
        }
    }
})